﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;

namespace Twi.COMMON.WPF
{
    public class ProcessHelper
    {
        /// <summary>
        /// 判断进程是否已经存在(用Process.GetProcess()方法获取的Process，难以判断Process.StartInfo.Arguments信息)
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public static bool ExistsProcess(string fileName, string arguments = "")
        {
            string wmiQuery = string.Format("select CommandLine from Win32_Process where Name like '{0}%'", fileName);
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
            ManagementObjectCollection retObjectCollection = searcher.Get();
            if (arguments == "") 
            {
                return retObjectCollection.Count > 0;
            }
            foreach (ManagementObject retObject in retObjectCollection)
            {
                string commandLine = retObject["CommandLine"].ToString();
                int lastDoubleQuoIndex = commandLine.LastIndexOf("\"");
                if (commandLine.Substring(lastDoubleQuoIndex + 1).Trim() == arguments)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
